﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using ENTIDADES;

namespace DATA
{
    public class PedidoDAO
    {
        public static Boolean grabarPedido(Pedido objPedido)
        {
            Boolean bolExito = false;

            Conexion strCNN = new Conexion();
            SqlConnection cnn = new SqlConnection(strCNN.obtenerConexion());
            cnn.Open();

            SqlTransaction transaction = cnn.BeginTransaction();

            try
            {
                String queryCabecera = "INSERT INTO cabecera_pedido (idmesa,idcliente,idempleado,fecha) VALUES (" + objPedido.objMesa.idmesa + "," + objPedido.objCliente.idcliente + "," + objPedido.objEmpleado.idempleado + ",CONVERT(DATE,GETDATE())) SELECT SCOPE_IDENTITY()";

                SqlCommand objComm = new SqlCommand(queryCabecera, cnn);

                objComm.Connection = cnn;
                objComm.Transaction = transaction;

                int idCabecera = Convert.ToInt32(objComm.ExecuteScalar());

                String queryDetalle = "INSERT INTO detalle_pedido (idproducto,cantidad,especificacion,idcabecerapedido,importe) VALUES ";

                foreach (DetallePedido obj in objPedido.lstDetallePedido)
                {
                    queryDetalle += "(" + obj.objProducto.idproducto + "," + obj.cantidad + ",'" + obj.especificacion + "'," + idCabecera + ","+ obj.cantidad*obj.objProducto.precio +"),";
                }

                queryDetalle = queryDetalle.Remove(queryDetalle.Length - 1);

                objComm = new SqlCommand(queryDetalle, cnn);
                objComm.Connection = cnn;
                objComm.Transaction = transaction;
                objComm.ExecuteNonQuery();

                if(!MesaDAO.getInstance().UpdateEstadoMesa(objPedido.objMesa.idmesa,1))
                {
                    transaction.Rollback();
                }

                transaction.Commit();
                bolExito = true;
            }

            catch (Exception ex)
            {
                transaction.Rollback();
            }

            cnn.Close();

            return bolExito;
        }
    }
}
